﻿using System;
using System.Collections.Generic;
using MdcService.Configuration;
using MdcService.Log;
using MdcService.Static;
using MdcService.Structure;
using MdcService.Structure.Enum;

namespace MdcService.Service
{
    public class ConfigurationService:IService
    {
        private IConfigurationManager<Configuration.Configuration> _configurationManager;
        private IConfigurationManager<IList<MachineDefinition>> _machineDefinitionManager;
        private RunningContext _runningContext;
        private ILogging _logging;


        public MdcService.Configuration.Configuration Configuration { get; set; }
        public IList<MachineDefinition> MachineDefinitions { get; set; }
        public event EventHandler<EventArgs> Started;
        public event EventHandler<EventArgs> Stopped;

        public ConfigurationService(IConfigurationManager<Configuration.Configuration> configurationManager,
            IConfigurationManager<IList<MachineDefinition>> machineDefinitionManager, RunningContext runningContext,
            ILogging logging)
        {
            //MachineDefinitions = new List<MachineDefinition>();

            _configurationManager = configurationManager;
            _machineDefinitionManager = machineDefinitionManager;
            _runningContext = runningContext;
            _logging = logging;
            this.Load();
            
           
        }

    
        public void Load(bool loadDefault = false)
        {
            this.Configuration = loadDefault ? new Configuration.Configuration() : _configurationManager.Load();
        }

        public void Save()
        {
            this._configurationManager.Save(this.Configuration);
        }

        public void LoadMachines()
        {
            this.MachineDefinitions = this._machineDefinitionManager.Load();
           
            
        }

        public void SaveMachines()
        {
            this._machineDefinitionManager.Save(this.MachineDefinitions);
        }

        public void SaveMachines(MachineDefinition machineDefinition)
        {
            this.MachineDefinitions.Add(machineDefinition);
            this._machineDefinitionManager.Save(this.MachineDefinitions);
        }

        public void Start()
        {
            
            if (_runningContext.ConfigurationServiceState== ServiceState.Running) return;

            LoadMachines();
            _runningContext.ConfigurationServiceState = ServiceState.Running;
            Started?.Invoke(this,new EventArgs());
        }

        public void Stop()
        {
            if (_runningContext.ConfigurationServiceState == ServiceState.Stopped) return;

            this.Save();
            SaveMachines();
            _runningContext.ConfigurationServiceState = ServiceState.Stopped;
            Stopped?.Invoke(this,new EventArgs());
        }

       

    }
}
